# 视频转语音API路由

from fastapi import APIRouter, Depends, UploadFile, File, Form, HTTPException, Header
from typing import Optional, Dict, Any, List

from ..core.video_processor import video_processor
from ..core.config import settings
from ..models.schemas import VideoToSpeechResponse, AudioExtractionResponse, ErrorResponse

router = APIRouter()

# 简单的API密钥验证依赖
async def verify_api_key(api_key: str = Header(None, alias=settings.API_KEY_HEADER)):
    """
    验证API密钥
    """
    if settings.API_KEY and settings.API_KEY != "":
        if not api_key:
            raise HTTPException(
                status_code=401,
                detail="缺少API密钥"
            )
        if api_key != settings.API_KEY:
            raise HTTPException(
                status_code=403,
                detail="API密钥无效"
            )
    return True

@router.post(
    "/video-to-speech",
    response_model=VideoToSpeechResponse,
    responses={
        400: {"model": ErrorResponse},
        401: {"model": ErrorResponse},
        403: {"model": ErrorResponse},
        500: {"model": ErrorResponse},
    },
    summary="视频转语音",
    description="上传视频文件并转换为语音",
    tags=["视频处理"],
)
async def convert_video_to_speech(
    file: UploadFile = File(..., description="视频文件"),
    language: Optional[str] = Form(None, description=f"语言代码，支持: {', '.join(settings.SUPPORTED_LANGUAGES)}"),
    speed: Optional[float] = Form(None, description="语音速度倍数，默认1.0"),
    _: bool = Depends(verify_api_key)
) -> Dict[str, Any]:
    """
    将上传的视频文件转换为语音
    """
    # 验证和映射语言代码
    if language:
        # 如果是完整的语言代码，尝试映射到简单代码
        if language in settings.LANGUAGE_CODE_MAPPING:
            language = settings.LANGUAGE_CODE_MAPPING[language]
        # 验证映射后的语言代码是否支持
        elif language not in settings.SUPPORTED_LANGUAGES:
            supported_codes = list(settings.SUPPORTED_LANGUAGES) + list(settings.LANGUAGE_CODE_MAPPING.keys())
            raise HTTPException(
                status_code=400,
                detail=f"不支持的语言代码: {language}。支持的语言: {', '.join(supported_codes)}"
            )
    
    # 验证语速
    if speed is not None and (speed <= 0 or speed > 3.0):
        raise HTTPException(
            status_code=400,
            detail="语速必须在0到3.0之间"
        )
    
    # 验证文件大小
    file_size_mb = 0
    file.file.seek(0, 2)  # 移动到文件末尾
    file_size_mb = file.file.tell() / (1024 * 1024)  # 转换为MB
    file.file.seek(0)  # 重置文件指针
    
    if file_size_mb > settings.MAX_VIDEO_SIZE_MB:
        raise HTTPException(
            status_code=400,
            detail=f"文件太大。最大允许大小: {settings.MAX_VIDEO_SIZE_MB}MB"
        )
    
    # 处理视频文件
    result = await video_processor.process_video_file(
        file, 
        language, 
        speed,
        extract_audio_only=False
    )
    
    return result

@router.post(
    "/extract-audio",
    response_model=AudioExtractionResponse,
    responses={
        400: {"model": ErrorResponse},
        401: {"model": ErrorResponse},
        403: {"model": ErrorResponse},
        500: {"model": ErrorResponse},
    },
    summary="提取视频音频",
    description="从视频文件中提取音频",
    tags=["视频处理"],
)
async def extract_audio_from_video(
    file: UploadFile = File(..., description="视频文件"),
    _: bool = Depends(verify_api_key)
) -> Dict[str, Any]:
    """
    从上传的视频文件中提取音频
    """
    # 验证文件大小
    file_size_mb = 0
    file.file.seek(0, 2)  # 移动到文件末尾
    file_size_mb = file.file.tell() / (1024 * 1024)  # 转换为MB
    file.file.seek(0)  # 重置文件指针
    
    if file_size_mb > settings.MAX_VIDEO_SIZE_MB:
        raise HTTPException(
            status_code=400,
            detail=f"文件太大。最大允许大小: {settings.MAX_VIDEO_SIZE_MB}MB"
        )
    
    # 处理视频文件，仅提取音频
    result = await video_processor.process_video_file(
        file, 
        extract_audio_only=True
    )
    
    return result

@router.get(
    "/supported-formats",
    summary="获取支持的视频格式",
    description="返回服务支持的视频格式列表",
    tags=["系统信息"],
)
async def get_supported_formats():
    """
    获取支持的视频格式列表
    """
    return {
        "formats": settings.SUPPORTED_VIDEO_FORMATS
    }

@router.get(
    "/supported-languages",
    summary="获取支持的语言",
    description="返回服务支持的语言列表",
    tags=["系统信息"],
)
async def get_supported_languages():
    """
    获取支持的语言列表
    """
    return {
        "languages": settings.SUPPORTED_LANGUAGES,
        "default": settings.DEFAULT_LANGUAGE
    }